package com.qianclass.talklive.app.fragment;

import android.app.Fragment;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.qianclass.talklive.R;
import com.qianclass.talklive.app.utils.LogUtil;

/**
 * Author:  Administrator-Li
 * Date:    2017/7/14 15:13
 * TODO:    
 */

public class VideoTextureFragment extends Fragment
        implements View.OnClickListener
{

    private static final int MESSAGE_ID_RECONNECTING = 0x01;

    private PLVideoTextureView mVideoView;
    private ProgressBar mLoadingView;
    private Toast mToast;
    private int mRotation = 0;
    private int mDisplayAspectRatio = PLVideoTextureView.ASPECT_RATIO_FIT_PARENT;
    private ImageButton mIbRotate;
    private ImageButton mIbSwitch;
    private String mVideoPath;
    public LinearLayout mLlSwitch;
    private View mView;
    private long mDuration;
    private PLMediaPlayer mPlMediaPlayer;
    private OnVideoPreparedListener mOnVideoPreparedListener;
    private OnVideoCompletionListener mOnVideoCompletionListener;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState)
    {
        mView = inflater.inflate(R.layout.fragment_video_texture, container);

        mVideoView = (PLVideoTextureView) mView.findViewById(R.id.VideoView);
        mLoadingView = (ProgressBar) mView.findViewById(R.id.LoadingView);
        mLlSwitch = (LinearLayout) mView.findViewById(R.id.ll_switch);
        mIbRotate = (ImageButton) mView.findViewById(R.id.ib_rotate);
        mIbSwitch = (ImageButton) mView.findViewById(R.id.ib_switch);
        mVideoView.setBufferingIndicator(mLoadingView);
        mLoadingView.setVisibility(View.VISIBLE);

        mIbRotate.setOnClickListener(this);
        mIbSwitch.setOnClickListener(this);

        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnErrorListener(mOnErrorListener);
        mVideoView.setOnPreparedListener(new PLMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(PLMediaPlayer plMediaPlayer, int i) {
                try {
                    if (mOnVideoPreparedListener != null) {
                        mOnVideoPreparedListener.onVideoPrepared(plMediaPlayer);
                    }

                    mPlMediaPlayer = plMediaPlayer;
                    mDuration = plMediaPlayer.getDuration();
                    LogUtil.e("duration", "duration:" + mDuration);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        Bundle arguments = getArguments();
        if (arguments != null) {
            mVideoPath = arguments.getString("videopath");
        }

        mVideoView.setVideoPath(mVideoPath);
        mVideoView.start();

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    public void onClickRotate() {
        mRotation = (mRotation + 90) % 360;
        mVideoView.setDisplayOrientation(mRotation);
    }

    public void onClickSwitchScreen() {
        mDisplayAspectRatio = (mDisplayAspectRatio + 1) % 5;
        mVideoView.setDisplayAspectRatio(mDisplayAspectRatio);
        switch (mVideoView.getDisplayAspectRatio()) {
            case PLVideoTextureView.ASPECT_RATIO_ORIGIN:
                showToastTips("Origin mode");
                break;
            case PLVideoTextureView.ASPECT_RATIO_FIT_PARENT:
                showToastTips("Fit parent !");
                break;
            case PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT:
                showToastTips("Paved parent !");
                break;
            case PLVideoTextureView.ASPECT_RATIO_16_9:
                showToastTips("16 : 9 !");
                break;
            case PLVideoTextureView.ASPECT_RATIO_4_3:
                showToastTips("4 : 3 !");
                break;
            default:
                break;
        }
    }

    private PLMediaPlayer.OnErrorListener mOnErrorListener = new PLMediaPlayer.OnErrorListener() {

        @Override
        public boolean onError(PLMediaPlayer mp, int errorCode) {

            boolean isNeedReconnect = false;
            switch (errorCode) {
                case PLMediaPlayer.ERROR_CODE_INVALID_URI:
                    showToastTips("Invalid URL !");
                    break;
                case PLMediaPlayer.ERROR_CODE_404_NOT_FOUND:
                    showToastTips("404 resource not found !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_REFUSED:
                    showToastTips("Connection refused !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_TIMEOUT:
                    showToastTips("Connection timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_EMPTY_PLAYLIST:
                    showToastTips("Empty playlist !");
                    break;
                case PLMediaPlayer.ERROR_CODE_STREAM_DISCONNECTED:
                    showToastTips("Stream disconnected !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_IO_ERROR:
                    showToastTips("Network IO Error !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_UNAUTHORIZED:
                    showToastTips("Unauthorized Error !");
                    break;
                case PLMediaPlayer.ERROR_CODE_PREPARE_TIMEOUT:
                    showToastTips("Prepare timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_READ_FRAME_TIMEOUT:
                    showToastTips("Read frame timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_HW_DECODE_FAILURE:
                    //setOptions(AVOptions.MEDIA_CODEC_SW_DECODE);
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.MEDIA_ERROR_UNKNOWN:
                    break;
                default:
                    showToastTips("unknown error !");
                    break;
            }
            if (isNeedReconnect) {
                sendReconnectMessage();
            }
            return true;
        }
    };

    private PLMediaPlayer.OnCompletionListener mOnCompletionListener = new PLMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(PLMediaPlayer plMediaPlayer) {
            //showToastTips("Play Completed !");
            mLoadingView.setVisibility(View.GONE);
            //stopVideoStream();
            if (mOnVideoCompletionListener != null && plMediaPlayer != null) {
                mOnVideoCompletionListener.onVideoCompletion(plMediaPlayer);
            }
        }
    };

    private void showToastTips(final String tips) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                }
                mToast = Toast.makeText(getActivity(), tips, Toast.LENGTH_SHORT);
                mToast.show();
            }
        });
    }

    private void sendReconnectMessage() {
        Log.e("=error=", "正在重连");
        showToastTips("正在重连...");
        mLoadingView.setVisibility(View.VISIBLE);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_ID_RECONNECTING), 500);
    }

    protected Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != MESSAGE_ID_RECONNECTING) {
                return;
            }
            if (!isNetworkAvailable(getActivity())) {
                sendReconnectMessage();
                return;
            }

            mVideoView.setVideoPath(mVideoPath);
            mVideoView.start();
        }
    };

    public boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_rotate:
                onClickRotate();
                break;
            case R.id.ib_switch:
                onClickSwitchScreen();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mVideoView.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        mToast = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
    }

    public void startVideoStream(){
        if (mVideoView != null) {
            mVideoView.start();
        }
    }

    public void stopVideoStream(){
        if (mVideoView != null) {
            mVideoView.stopPlayback();
            mVideoView = null;
        }
    }

    public void seekTo(int progress){
        if (mVideoView != null) {
            mVideoView.seekTo(progress);
        }
    }

    public void playOrPauseVideo(boolean play){
        if (play) {
            //播放
            if (mVideoView != null && !mVideoView.isPlaying()) {
                mVideoView.start();
            }
        } else {
            //暂停
            if (mVideoView != null && mVideoView.isPlaying()) {
                mVideoView.pause();
            }
        }
    }


    /****视频准备完成的监听****/
    public void setOnPreparedListener(OnVideoPreparedListener listener){
        mOnVideoPreparedListener = listener;
    }

    public interface OnVideoPreparedListener{
        void onVideoPrepared(PLMediaPlayer plMediaPlayer);
    }

    /****视频播放完成的监听****/
    public void setOnCompletionListener(OnVideoCompletionListener listener){
        mOnVideoCompletionListener = listener;
    }

    public interface OnVideoCompletionListener{
        void onVideoCompletion(PLMediaPlayer plMediaPlayer);
    }
}
